﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using System.Data;

namespace Demo.Common
{
    /// <summary>
    /// JSON帮助类
    /// </summary>
    public class JsonHelper
    {
        /// <summary> 
        /// 对象转JSON 
        /// </summary> 
        /// <param name="obj">对象</param> 
        /// <returns>JSON格式的字符串</returns> 
        public static string ObjectToJSON(object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            var json = jss.Serialize(obj);
            //将时间格式转换为适合阅读习惯的格式
            json = System.Text.RegularExpressions.Regex.Replace(json, @"\\/Date\((\d+)\)\\/", match =>
            {
                DateTime dt = new DateTime(1970, 1, 1);
                dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
                dt = dt.ToLocalTime(); //本地时间
                return dt.ToString(); ;
            });
            try
            {
                byte[] b = Encoding.UTF8.GetBytes(json);
                return Encoding.UTF8.GetString(b);
            }
            catch (Exception ex)
            {

                throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
            }
        }

        /// <summary> 
        /// 数据表转键值对集合
        /// 把DataTable转成 List集合, 存每一行 
        /// 集合中放的是键值对字典,存每一列 
        /// </summary> 
        /// <param name="dt">数据表</param> 
        /// <returns>哈希表数组</returns> 
        public static List<Dictionary<string, object>> DataTableToList(DataTable dt)
        {
            List<Dictionary<string, object>> list
                 = new List<Dictionary<string, object>>();

            foreach (DataRow dr in dt.Rows)
            {
                Dictionary<string, object> dic = new Dictionary<string, object>();
                foreach (DataColumn dc in dt.Columns)
                {
                    dic.Add(dc.ColumnName, dr[dc.ColumnName]);
                }
                list.Add(dic);
            }
            return list;
        }

        /// <summary> 
        /// 数据集转键值对数组字典 
        /// </summary> 
        /// <param name="dataSet">数据集</param> 
        /// <returns>键值对数组字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> DataSetToDic(DataSet ds)
        {
            Dictionary<string, List<Dictionary<string, object>>> result = new Dictionary<string, List<Dictionary<string, object>>>();

            foreach (DataTable dt in ds.Tables)
                result.Add(dt.TableName, DataTableToList(dt));

            return result;
        }

        /// <summary> 
        /// 数据表转JSON 
        /// </summary> 
        /// <param name="dataTable">数据表</param> 
        /// <returns>JSON字符串</returns> 
        public static string DataTableToJSON(DataTable dt)
        {
            return ObjectToJSON(DataTableToList(dt));
        }

        /// <summary> 
        /// JSON文本转对象,泛型方法 
        /// </summary> 
        /// <typeparam name="T">类型</typeparam> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>指定类型的对象</returns> 
        public static T JSONToObject<T>(string jsonText)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Deserialize<T>(jsonText);
            }
            catch (Exception ex)
            {
                throw new Exception("JSONHelper.JSONToObject(): " + ex.Message);
            }
        }

        /// <summary> 
        /// 将JSON文本转换为数据表数据 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据表字典</returns> 
        public static Dictionary<string, List<Dictionary<string, object>>> TablesDataFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, List<Dictionary<string, object>>>>(jsonText);
        }

        /// <summary> 
        /// 将JSON文本转换成数据行 
        /// </summary> 
        /// <param name="jsonText">JSON文本</param> 
        /// <returns>数据行的字典</returns>
        public static Dictionary<string, object> DataRowFromJSON(string jsonText)
        {
            return JSONToObject<Dictionary<string, object>>(jsonText);
        }

        #region Property

        /// <summary>
        /// 数据状态
        /// </summary>
        public string Status { get; set; } = "";

        /// <summary>
        /// 提示信息
        /// </summary>
        public string Msg { get; set; } = "";

        /// <summary>
        /// json
        /// </summary>
        public string JsonData { get; set; } = "";

        /// <summary>
        /// 数据包
        /// </summary>
        public object[] Data { get; set; } = new object[] { };

        public int? TotalCount { get; set; } = 0;
        #endregion
        /// <summary>
        /// 返回状态，消息和对象
        /// </summary>
        /// <param name="status">状态</param>
        /// <param name="msg">消息</param>
        /// <param name="data">对象</param>
        /// <returns></returns>
        public static JsonHelper New(string status, string msg)
        {
            return new JsonHelper() { Status = status, Msg = msg };
        }

        /// <summary>
        /// 返回状态，消息和对象
        /// </summary>
        /// <param name="status">状态</param>
        /// <param name="msg">消息</param>
        /// <param name="data">对象</param>
        /// <returns></returns>
        public static JsonHelper New(string status, string msg, object data = null)
        {
            return new JsonHelper() { Status = status, Msg = msg, JsonData = ObjectToJSON(data) };
        }
        public static JsonHelper New(string status, string msg, object[] data = null)
        {
            if (data == null)
            {
                data = new object[] { };
            }
            return new JsonHelper() { Status = status, Msg = msg, Data = data };
        }
        public static JsonHelper New(string status, string msg, object[] data = null, string salt = null)
        {
            if (data == null)
            {
                data = new object[] { };
            }
            return new JsonHelper() { Status = status, Msg = msg, Data = data, JsonData = salt };
        }
        public static JsonHelper New(string status, string msg, object[] data = null, int totalCount = 0)
        {
            if (data == null)
            {
                data = new object[] { };
            }
            return new JsonHelper() { Status = status, Msg = msg, Data = data, TotalCount = totalCount };
        }
        /// <summary>
        /// 返回状态，消息和对象
        /// </summary>
        /// <param name="status">状态</param>
        /// <param name="msg">消息</param>
        /// <param name="data">对象</param>
        /// <returns></returns>
        public static JsonHelper New(string status, string msg, string data = null)
        {
            return new JsonHelper() { Status = status, Msg = msg, JsonData = data };
        }
        /// <summary>
        /// 返回状态，消息和json数据表
        /// </summary>
        /// <param name="status">状态</param>
        /// <param name="msg">消息</param>
        /// <param name="dt">数据表</param>
        /// <returns></returns>
        public static JsonHelper New(string status, string msg, DataTable dt)
        {
            if (dt != null)
            {
                return new JsonHelper() { Status = status, Msg = msg, JsonData = DataTableToJSON(dt) };
            }
            else
            {
                return new JsonHelper() { Status = status, Msg = msg };
            }
        }
        /// <summary>
        /// 返回状态，消息和json数据表
        /// </summary>
        /// <param name="status">状态</param>
        /// <param name="msg">消息</param>
        /// <param name="dt">数据表</param>
        /// <param name="totalcount">总页数</param>
        /// <returns></returns>
        public static JsonHelper New(string status, string msg, DataTable dt, int totalcount)
        {
            if (dt != null)
            {
                return new JsonHelper() { Status = status, Msg = msg, JsonData = DataTableToJSON(dt), TotalCount = totalcount };
            }
            else
            {
                return new JsonHelper() { Status = status, Msg = msg };
            }
        }
    }
}